//初始化函数调用
$(function () {
    initTable();
   // initDate();
});
//获取配置名称
var confNames;
$.ajax({
    url: "http://61.147.166.206:8963/gpumall/Configure/listAllConfig",
    type: 'get',
    dataType: "json",
    success:function(result){
        confNames = result.data;
    }});

//刷新表格
function doQuery(params){
    $('#demo-table').bootstrapTable('refresh');
    $("#submitterName").val("");
    $("#submitterTel").val("");
}

function initTable(){
    var url = "http://61.147.166.206:8963/gpumall/MyOrder/queryOrder";
    $('#demo-table').bootstrapTable({
        method:'get',
        dataType:'json',
        contentType: "application/x-www-form-urlencoded",
        cache: false,
        striped: true,                              //是否显示行间隔色
        sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
        url:url,
        height: $(window).height()-160,
        width:$(window).width(),
        pagination:true,
        queryParams : queryParams,
        minimumCountColumns:2,
        pageNumber:1,                       //初始化加载第一页，默认第一页
        pageSize: 15,                         //每页的记录行数（*）
        pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
        uniqueId: "id",                     //每一行的唯一标识，一般为主键列
        responseHandler: responseHandler,
        columns: [
            {
                field: '',
                title: '序号',
                formatter: function (value, row, index) {
                    //显示行号，分页可用
                    var pageSize=$('#demo-table').bootstrapTable('getOptions').pageSize;
                    var pageNumber=$('#demo-table').bootstrapTable('getOptions').pageNumber;
                    return pageSize * (pageNumber - 1) + index + 1;
                }
            },
            {
                field : 'submitterName',
                title : '姓名',
                align : 'center',
                width : '10%',
                valign : 'middle'
            }, {
                field : 'submitterTel',
                title : '电话',
                align : 'center',
                width : '20%',
                valign : 'middle'
            }, {
                field : 'submitterCompany',
                title : '地址',
                align : 'center',
                width : '40%',
                valign : 'middle'
            }, {
                field : 'submitDate',
                title : '下单日期',
                align : 'center',
                width : '20%',
                valign : 'middle',
                formatter: function (value,row,index) {        //时间戳转化成日期格式
                    return row.submitDate = new Date(row.submitDate).toLocaleString();
                }
            }, {
                title : '操作',
                align : 'center',
                width : '10%',
                valign : 'left',
                events: operateEvents,
                formatter :Operate
            }]
    });
}

//查询参数
function queryParams(params) {
    var param = {
        submitterName : $("#submitterName").val(),
        submitterTel : $("#submitterTel").val(),
        pageNumber : this.pageNumber,
        pageSize : this.pageSize
    };
    return param;
}

//获取数据后处理函数
function responseHandler(result) {

    if (result.data) {
        return {
            "rows" : result.data.rows,
            "total" : result.data.total
        };
    } else {
        return {
            "rows" : [],
            "total" : 0
        };
    }
}

//操作
function Operate(value,row,index) {
    return '<a type="button" class="details btn btn-sm btn-info" data-toggle="modal">详情</a>' + '&nbsp;&nbsp;' +
        '<a type="button" class="mod btn  btn-sm btn-success" data-toggle="modal">修改</a>';
}
window.operateEvents = {
    'click .details': function (e, value, row) {
        var totalprices = 0;  //总价
        $("#name").html(row.submitterName);
        $("#telehpone").html(row.submitterTel);
        $("#address").html(row.submitterCompany);
        //遍历配置
        $.each(row.goodsJoList, function(index, item) {
            var configId = item.configId
            var pid =  confNames[configId].pid;
            var name = confNames[item.configId].name +'【'+confNames[pid].name+'】';  //配置名称
            var rowTem = '<tr>'
                + '<td>' + name + '</td>'
                + '<td>' + item.count + '</td>'
                + '<td>'+ item.totalPrice +'</td>'
                + '</tr>';
            totalprices += item.totalPrice;
            $("#detail tbody:last").append(rowTem);
        });
        $("#totalprices").html(totalprices);
        $("#details").modal('show');
    },
    'click .mod': function (e, value, row) {   //填入订单信息
        $("#mod-id").val(row.id);
        $("#mod-name").val(row.submitterName);
        $("#mod-telehpone").val(row.submitterTel);
        $("#mod-address").val(row.submitterCompany);
        $.each(row.goodsJoList, function(index, item) {
            var pid =  confNames[item.configId].pid;
            var name = confNames[item.configId].name +'【'+confNames[pid].name+'】';  //配置名称
            var rowTem = '<tr>'
                + '<td class="configId">' + goodOption (pid,item.configId) + '</td>'
                + '<td>'+'<input style="width: 90%" class="form-control number" value="'+item.count+'" onchange="countChange(this)"></td>'
                + '<td>'+'<input style="width: 90%" class="form-control count" value="'+item.totalPrice +'" disabled></td>'
                +'<td>'+goodsDeleteBtn(pid)+'</td>'
                + '</tr>';
            totalprices += item.totalPrice;
            $("#mod-detail tbody:last").append(rowTem);
        });
        totalPrice();
        $("#mod-goods").modal('show');
    }
};
//移除循环添加的tr配置行
$('#details').on('hide.bs.modal', function () {
    $("#peizhi").nextAll().remove();
});
$('#mod-goods').on('hide.bs.modal', function () {
    $("#mod-peizhi").nextAll().remove();
});

//添加商品
function addGood() {

    var rowTem = '<tr>' +
        '<td class="configId">'+addGoodOpt()+'</td>' +
        '<td><input style="width: 90%" class="form-control number" value="1" onchange="countChange(this)"></td>' +
        '<td><input style="width: 90%" class="form-control count" value="0" disabled></td>' +
        '<td><button class="btn btn-danger btn-xs" onclick="deleteGoods(this)">删除</button></td>' +
        '</tr>';
    $("#mod-detail tbody:last").append(rowTem);
}
//添加商品后四项下拉
function addGoodOpt() {
    var pids = [5,6,7,35];
    var options = '<select class="form-control peizhi" style="width: 95%" onchange="peizhiChange(this)">';
    for(var i=0;i < pids.length;i++){
        var id = pids[i];
        var goods = confNames[id].child.split(",");
        for(var j=0;j < goods.length;j++){
            var childId = goods[j];
            options +=  '<option value="'+confNames[childId].id+'">'+confNames[childId].name+'【'+confNames[id].name+'】'+'</option>';
        }
    }
    return options +='</select>';
}

//商品下拉----修改
function goodOption (pid,configId) {
    var pgoods = confNames[pid].child.split(","); //获取小类id
    var options = '<select  class="form-control peizhi" style="width: 95%" onchange="peizhiChange(this)">';
    for(var i=0;i < pgoods.length;i++) {
        var childId = pgoods[i];
        if(confNames[childId].id == configId){
            options +=  '<option value="'+confNames[childId].id+'" selected>'+confNames[childId].name+'【'+confNames[pid].name+'】'+'</option>';
        }else {
            options +=  '<option value="'+confNames[childId].id+'">'+confNames[childId].name+'【'+confNames[pid].name+'】'+'</option>';
        }
    }
    return options +='</select>';
}
//前四类商品下拉禁止删除按钮
function goodsDeleteBtn(pid) {
    if(pid ==1||pid ==2||pid ==3||pid ==4){
        return '<button class="btn btn-danger btn-xs" disabled>删除</button>';
    }
    else {
        return '<button class="btn btn-danger btn-xs" onclick="deleteGoods(this)">删除</button>';
    }

}

//删除商品
function deleteGoods(thisdel) {
    thisdel.parentNode.parentNode.remove(thisdel.parentNode);
    totalPrice();
}

//计算某类商品的价格----当商品配置改变时
function peizhiChange(thiscat) {
    var goodId = parseInt($(thiscat).val());
    var goodPrice = confNames[goodId].price * $(thiscat).parents('tr').find('input.number').eq(0).val();  //价格计算
    $(thiscat).parents('tr').find('input.count').eq(0).val(goodPrice); //价格写入
    totalPrice();
    console.log(goodId)
    console.log(goodPrice)
}
//计算某类商品的价格----当商品数量改变时
function countChange(thisCount) {
    var goodCount = $(thisCount).val();
    var goodId = parseInt($(thisCount).parents('tr').find('select.peizhi').eq(0).val());
    var goodPrice = confNames[goodId].price * goodCount;  //价格计算
    $(thisCount).parents('tr').find('input.count').eq(0).val(goodPrice); //价格写入
    totalPrice();
    console.log(goodCount)
    console.log(goodPrice)
}
//计算总价并展示
function totalPrice() {
    var toPrice = 0;
    $(".count").each(function(){
        toPrice += parseInt($(this).val());
    });

    $("#mod-totalprices").html(toPrice);
    console.log(toPrice)
}

//更新订单
function updateOrder() {
    $.ajax({
        url: "http://61.147.166.206:8963/gpumall/MyOrder/updateOrder",
        type: 'post',
        data: {
            id:parseInt($("#mod-id").val()),
            submitterName:$("#mod-name").val(),
            submitterTel:$("#mod-telehpone").val(),
            submitterCompany:$("#mod-address").val()
        },
        dataType: "json",
        success:function(result){
            if(result.resultFlag == true){
                alert("用户信息更改成功！");
                $('#mod-goods').on('hide.bs.modal', function () {
                    $("#mod-peizhi").nextAll().remove();
                });
            }else{
                alert("更改失败！");
            }
        }});
}

//保存更改商品
function peizhiSave() {
    var goodsParams ='s';
    var peizhiIds = new Array();
    var numbers = new Array();
    var counts = new Array();
    $(".peizhi").each(function(){  //获取参数
        peizhiIds.push($(this).val());
    });
    $(".number").each(function(){
        numbers.push($(this).val());
    });
    $(".count").each(function(){
        counts.push($(this).val());
    });
    console.log(numbers);
    console.log(counts);
    console.log(peizhiIds);
    for(var i=0;i < peizhiIds.length;i++){   //格式化参数
        goodsParams = goodsParams + peizhiIds[i]+','+numbers[i]+','+counts[i]+';';
    }
    goodsParams = goodsParams.substr(1,goodsParams.length-2);
    console.log(goodsParams);
    $.ajax({                                                 //保存
        url: "http://61.147.166.206:8963/gpumall/MyOrder/rewriteGoodsOfOrder",
        type: 'post',
        data: {
            orderId: parseInt($("#mod-id").val()),
            goodsInfo: goodsParams
        },
        dataType: "json",
        success:function(result){
            if(result.resultFlag == true){
                alert("更改成功！");
                $('#mod-goods').modal('hide');    //隐藏静态框
                $('#demo-table').bootstrapTable('refresh'); //刷新列表
            }else{
                alert("更改失败！请检查是否重复添加商品配置");
                $('#demo-table').bootstrapTable('refresh'); //刷新列表
            }
        }});
}
